package orders

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"github.com/shopspring/decimal"
	"github.com/spf13/cast"
	"gorm.io/gorm"
	"insighttracking/apps/sorting/auth"
	"insighttracking/common/enum"
	"insighttracking/common/utils"
	"insighttracking/query/bo"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/sorting/internal/svc"
	"insighttracking/apps/sorting/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetOrdersPageApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetOrdersPageApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetOrdersPageApiLogic {
	hostname, _ := os.Hostname()
	return &GetOrdersPageApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetOrdersPageApiLogic) GetOrdersPageApi(req *types.GetOrdersPageReq) (resp *types.GetOrdersPageResp, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return nil, err
	}
	ordersBo, count, err := service.OrdersService.GetPageApi(l.ctx, bo.OrdersPageBoReq{
		EnterpriseID:       accountInfo.EnterpriseId,
		OrderNo:            req.OrderNo,     // 订单流水号
		Status:             req.Status,      // 订单状态,0表示已下单(待采购),10分拣中，20已发货,30已完成,40取消订单
		StartDate:          req.StartDate,   // 开始时间，时间格式为:2024-12-12
		EndDate:            req.EndDate,     // 结束时间, 时间格式为:2024-12-12
		WarehouseID:        req.WarehouseID, // 仓库id
		Name:               req.Name,        // 商品名称
		PageSize:           req.PageSize,    // 当前条数
		PageNumber:         req.PageNumber,  // 当前页数
		GoodsDateStartDate: req.GoodsDateStartDate,
		GoodsDateEndDate:   req.GoodsDateEndDate,
		StatusList:         []int64{enum.OrdersCreateEnum, enum.OrdersSortingProgressEnum, enum.OrdersSortingFinishEnum, enum.OrdersAlreadyShippedEnum, enum.OrdersCompletedEnum},
	})
	if err != nil || len(ordersBo) == 0 {
		return &types.GetOrdersPageResp{
			Data: make([]types.GetOrdersResp, 0),
			PageBaseResp: types.PageBaseResp{
				Total:      0,
				PageSize:   req.PageSize,
				PageNumber: req.PageNumber,
			},
		}, nil
	}
	var result = make([]types.GetOrdersResp, 0)
	for _, item := range ordersBo {
		detailEntities, err := service.OrdersDetailService.GetByOrderIdListApi(l.ctx, []int64{item.ID})
		orderDetailIdList := k.Map(detailEntities, func(item *model.OrdersDetailEntity, index int) int64 {
			return item.ID
		})
		ordersWeight := decimal.Zero // 订单总重量
		for _, item1 := range detailEntities {
			ordersWeight = ordersWeight.Add(item1.SpuCount)
		}
		entities, err1 := service.StoreSortingDetailService.GetStoreSortingDetailByOrdersDetailIdListApi(l.ctx, orderDetailIdList)
		var completeOrdersCount = decimal.Zero
		for _, item1 := range entities {
			completeOrdersCount = completeOrdersCount.Add(item1.OutboundCount)
		}
		// 查询详情
		var outStatus int64 // 出库状态 0表示待出库,10已出库，20部分出库,30已发货
		if k.IsContains([]int64{enum.OrdersAlreadyShippedEnum, enum.OrdersCompletedEnum}, item.Status) {
			outStatus = 30
		} else {
			goodsRecordEntity, err := service.SendGoodsRecordService.GetStoreSortingByOrderIdApi(l.ctx, item.ID)
			if !errors.Is(err, gorm.ErrRecordNotFound) {
				detailEntities, err := service.OrdersDetailService.GetByOrderIdListApi(l.ctx, []int64{item.ID})
				storeDetailEntities, err := service.SendGoodsRecordDetailService.GetSendGoodsRecordDetailApi(l.ctx, goodsRecordEntity.ID)
				if err == nil && len(detailEntities) > 0 {
					if len(storeDetailEntities) >= len(detailEntities) {
						outStatus = 10
					} else {
						outStatus = 20
					}
				}
			}
		}
		var inStatus = service.PurchaseOrderService.GetPurchaseOrderStatusByOrderIdApi(l.ctx, item.ID) // 入库状态 0表示待入库,10已入库
		result = append(result, types.GetOrdersResp{
			ID:                        item.ID,                                                                           // 主键id
			OrderNo:                   item.OrderNo,                                                                      // 订单流水号
			CustomerID:                item.CustomerID,                                                                   // 客户id,关联到enterprise_customer表主键id
			CustomerName:              item.CustomerName,                                                                 // 门店名称
			SendGoodsDate:             k.If(item.SendGoodsDate.IsZero(), 0, utils.TimestampToString(item.SendGoodsDate)), // 发货日期
			SendGoodsMethod:           item.SendGoodsMethod,                                                              // 发货方式,0表示司机配送
			SettlementMethod:          item.SettlementMethod,                                                             // 结算方式，0表示账期
			PurchaserID:               item.PurchaserID,                                                                  // 采购员,关联到
			PurchaserName:             item.PurchaserName,                                                                // 采购员名称
			Remark:                    item.Remark,                                                                       // 订单备注
			TotalAmount:               item.TotalAmount.StringFixed(2),                                                   // 订单金额
			Status:                    item.Status,                                                                       // 订单状态,0表示已下单(待采购),1表示采购中,2表示已采购,3待入库，4已入库，5已发货,6已收货,7表示退货
			ReceiveGoodsName:          item.ReceiveGoodsName,                                                             // 收货员姓名
			ReceiveGoodsMobile:        item.ReceiveGoodsMobile,                                                           // 收货人手机号码
			ReceiveAddress:            item.ReceiveAddress,                                                               // 收货人地址
			IsPurchasingPlan:          item.IsPurchasingPlan,                                                             // 是否发布采购计划,0表示不发布,1表示发布
			Source:                    item.Source,                                                                       // 订单来源,0表示app端,1表示pc下单
			SettlementStatus:          item.SettlementStatus,                                                             // 结算状态，0表示未结算,1表示已结算
			SendGoodsID:               item.SendGoodsID,                                                                  // 配置司机,关联到account表主键id
			SendGoodsName:             item.SendGoodsName,                                                                // 配送司机名称
			WarehouseID:               item.WarehouseID,                                                                  // 发货仓库,关联到warehouse表主键id
			WarehouseName:             item.WarehouseName,                                                                // 仓库名称
			CreatedAt:                 utils.TimestampToString(item.CreatedAt),                                           // 创建时间
			UpdatedAt:                 utils.TimestampToString(item.UpdatedAt),                                           // 更新时间
			OrdersCount:               item.TotalCount.StringFixed(2),                                                    // 订单数量
			CompleteOrdersCount:       completeOrdersCount.StringFixed(2),                                                // 完成订单数量
			OrdersDetailCount:         cast.ToString(k.If(err == nil, len(detailEntities), 0)),                           // 订单中种类
			CompleteOrdersDetailCount: cast.ToString(k.If(err1 == nil, len(entities), 0)),                                // 完成分拣种类数量
			OutStatus:                 outStatus,                                                                         // 出库状态 0表示待出库,10已出库，20部分出库,30已发货
			InStatus:                  inStatus,                                                                          // 入库状态 0表示待入库,10已入库
			OrdersWeight:              ordersWeight.StringFixed(2),                                                       // 订单总重量
			CompleteOrdersWeight:      completeOrdersCount.StringFixed(2),                                                // 完成分拣重量
		})
	}
	return &types.GetOrdersPageResp{
		Data: result,
		PageBaseResp: types.PageBaseResp{
			Total:      count,
			PageSize:   req.PageSize,
			PageNumber: req.PageNumber,
		},
	}, nil
}
